<?php
require_once('BaseController.php');
/**
 * M&oacute;dulo de conteudos do Site
 * @author Gedalias
 * @name Conteudo
 * @label Conte&uacute;do
 * @menu 1
 * @menu_secao Conte&uacute;do
 */

class Third_ConteudoController extends BaseController
{
	protected $name = 'conteudo';
	protected $configFile = 'third_conteudo';
	protected $categorias;
	
	public function init()
	{
		parent::init();
		$this->categorias = $this->getCategorias();
		$this->view->assign('categorias', $this->categorias );
		
		//LOAD DAO
		require_once('Conteudo.php');
		$this->dao = new Conteudo();
		
	}

	/**
	 * Listar conteudos
	 * @menu 1
	 * @order 1
	 */
	public function indexAction()
	{
		$conteudo = "";
		$id = $this->getRequest()->getParam('id');
		
		$categoriaAtual = $this->getCategoriaAtual( $id );
		if( $categoriaAtual ){
			switch( $categoriaAtual['tipo'] ){
				case 'Pagina':
					$conteudo = $this->dao->getById( $id , 'categorias_id' );
					if( !$conteudo ){
						$conteudoData = array(
							'titulo'=>$categoriaAtual['titulo'],
							'categorias_id'=>$id,
							'sites_id'=>$this->_logged->sites_id,
							'criado_em'=>Third_Funcs::getDate('now', 'datetime')
						);
						$objectId = $this->dao->insert( $conteudoData );
						if( $objectId ){
							$conteudo = $this->dao->getById( $id , 'categorias_id' );
						}
					}
				break;
				default:
					$conteudo = $this->dao->getAllBySite( $id , 'categorias_id' );
				break;
			}

			$this->view->assign('categoria', $categoriaAtual );
			$this->view->assign('conteudo', $conteudo );
		}
	}

	public function getCategoriaAtual( $id ){
		$findCategoria = Third_Funcs::multiarraySearch( $this->categorias , 'id', $id );
		$categoriaAtual = reset( $findCategoria );
		return $categoriaAtual; 
	}
	
	/**
	 * Adicionar conteudo
	 * @menu 1
	 * @order 1
	 */
	public function addAction(){
		$id = $this->getRequest()->getParam('categoria');
		
		$categoria = $this->getCategoriaAtual( $id );
		
		$this->view->assign('categoria', $categoria );
		
		$form = $this->getFormProfile();
		
		$form->setAction('/third/conteudo/add');
		$form->removeElement('permalink');
		$form->removeElement('status');
		$form->removeElement('id');
		
		if( $categoria ){
			$form->getElement('categorias_id')->setValue( $categoria );
		}
		
		$data = $this->getRequest()->getPost();
					
		if( $this->getRequest()->isPost() ){
			if( $form->isValid( $data )) {
					$saveData = array(
						'sites_id'=>$this->_site['id'],
						'permalink'=>Third_Funcs::generatePermalink($data['titulo']),
						'titulo'=>$data['titulo'],
						'texto'=>$data['texto'],
						'status'=>0,
						'categorias_id'=>$data['categorias_id'],
						'criado_em'=>Third_Funcs::getDate('now', 'datetime'),
						'atualizado_em'=>Third_Funcs::getDate('now', 'datetime')
					);

					try{
						$objetoId = $this->dao->insert( $saveData );

						//LOG OPERATIONS
						$this->log('insert', 'SUCCESS', $this->dao->getName(), $id );
						$this->flash('Conte&uacute;do cadastrado com sucesso.', 'success', '/third/'.$this->name."/index/id/".$data['categorias_id'] );

						echo true;
					} catch( Zend_Exception $e ){
						//LOG OPERATIONS
						$this->log('insert', 'CRITICAL_DB_INSERT_ERROR', $this->dao->getName() );
						$this->flash('Erro ao cadastrar conte&uacute;do.', 'error', '/third/'.$this->name."/index/id/".$data['categorias_id'] );

						echo false;
					}
			
			} else {
				$this->view->assign('formErro','Por favor, verifique os erros informados.');
				$form->populate( $data );
			}
		}

		$this->view->assign('form', $form );
	}
	
	/**
	 * Editar conteudo
	 */
	public function editAction(){
		$conteudo = $this->getRequest()->getParam('conteudo');

		if( !$conteudo ){
			
		}

		$this->view->assign('conteudo', $conteudo );

		$form = $this->getFormProfile();
		if( $conteudo ){
			$form->populate( $conteudo );
		}

		$this->view->assign('form', $form );
	}
	
	/**
	 * Pega profile do formularios de acesso
	 * @return Third_Form
	 */
	public function getFormProfile(){
	    //FORMULARIO DE LOGIN
		$formLogin = null;

		$formConfig = $this->configs->form;

		if( $formConfig ){
			$form = new Third_Form( $formConfig );
			
			Third_Funcs::addSelectOptions( $form->getElement('categorias_id') , $this->categorias );
		} 

		return $form;
	}
	
	/**
	 * Retorna categorias
	 * @return $paginator
	 */
	public function getCategorias(){
		require_once("Categorias.php");
		$dao = new Categorias();
		
		$dao->setPage( $this->getRequest()->getParam('page', 0 ) );
		
		$search = $this->getRequest()->getParam('search'); 
		$pagesize = $this->getRequest()->getParam('pagesize');
		$index  = $this->getRequest()->getParam('sidx'); 
		$order  = $this->getRequest()->getParam('sord'); 

		//INDEX
		$select = $dao->getSelectObject();


		//QUANTIDADE DE REGISTROS
		if( $pagesize ){ 
			$dao->setQuantidadePaginacao( $pagesize );
			$this->view->assign('pagesize', $pagesize );
		}

		//BUSCA
		if( $search ){
			$select->where('nome LIKE "%'.$search.'%"');	
			$this->view->assign('search', $search );
		}

		//EXECUTA
		$dao->setSelectObject( $select );

		return $dao->getCategoriasTree( array('all'=>true) );
	}
}

